﻿
@{
    ViewBag.Title = "Kpi實際";
    ViewBag.PageInfo = "Kpi/KpiMain";//Kpi/KpiAct
    ViewBag.Month = DateTime.Now.Month == 1 ? (12).ToString() : (DateTime.Now.Month - 1).ToString();
    ViewBag.TdWidth = "100%";
    ViewBag.TaWidth = "120px";
    ViewBag.TfCs = 5;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@*右鍵菜單*@
<style>
    #actkpimenu {
        display: none;
        /*height: 320px;*/
        width: 240px;
        position: absolute;
        z-index: 9999;
        background-color: #ffffff;
        border: 1px solid #ffffff;
        border-radius: 8px;
        box-shadow: 2px 2px 8px 2px #c4c4c4;
    }

    .actkpimenu-item {
        height: 35px;
        line-height: 35px;
        padding: 0 10px;
        cursor: default;
    }

        .actkpimenu-item:hover {
            border-radius: 8px;
            background-color: #f1f1f1;
        }

    .select_item {
        position: relative;
        margin-left: 0px;
        width: 162px;
        height: 10px;
    }
</style>
<div id="actkpimenu">
</div>
<script>
    var actwidth = window.innerWidth;
    var actheight = window.innerHeight;
    //重新计算窗口大小
    window.addEventListener('resize', () => {
        actwidth = window.innerWidth;
        actheight = window.innerHeight;
    })
    var actkpimenu = document.querySelector("#actkpimenu");
    window.oncontextmenu = function (e) {
        //取消瀏覽器默認右鍵菜單
        e.preventDefault();
        var tableTitle = $("#KpiActDataTd table thead tr")[0].children;
        var data = "";
        for (var i = 3; i < 16; i++) {
            if (actkpimenu.innerHTML == '\n') {
                data += '<div class="actkpimenu-item" data-id="' + i + '"><input class="actkpicheck-item" type="checkbox" checked="checked" onchange="actkpiHideCol(' + i + ', event)" />&nbsp;&nbsp;' + tableTitle[i].innerHTML.replace("<br>", "") + '</div>';
            } else {
                if (actkpimenu.children[i - 3].children[0].checked) {
                    data += '<div class="actkpimenu-item" data-id="' + i + '"><input class="actkpicheck-item" type="checkbox" checked="checked" onchange="actkpiHideCol(' + i + ', event)" />&nbsp;&nbsp;' + tableTitle[i].innerHTML.replace("<br>", "") + '</div>';
                } else {
                    data += '<div class="actkpimenu-item" data-id="' + i + '"><input class="actkpicheck-item" type="checkbox" onchange="actkpiHideCol(' + i + ', event)" />&nbsp;&nbsp;' + tableTitle[i].innerHTML.replace("<br>", "") + '</div>';
                }
            }
        }
        //data += '<div class="actkpimenu-item" id="monthInfo" data-id="0">&#12288;&nbsp;月份信息&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;▷';
        //if (tableTitle.length == 24) {
        //    //默認月份
        //    data += '<div id="lv2" class="lvmenu">';
        //    for (var i = 16; i < 24; i += 4) {
        //        data += '<div class="actkpimenu-item" id="info'+i+'" data-id="0">&#12288;&nbsp;' + tableTitle[i].innerHTML + '&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;▷';
        //        data += '<div id="lv3' + i + '" class="lvmenu">';
        //        for (var j = 0; j < 4; j++) {
        //            data += '<div class="actkpimenu-item" data-id="' + (i + j) + '"><input type="checkbox" checked="checked" onchange="actkpiHideCol(' + (i + j) + ', event)" />&nbsp;&nbsp;' + tableTitle[i + j].innerHTML.replace("<br>", "") + '</div>';
        //        }
        //        data += '</div>';
        //        data += '</div>';
        //    }
        //    data += '</div>';
        //} else {
        //    //所有月份
        //    data += '<div id="lv2">';
        //    for (var i = 16; i < 64; i += 4) {
        //        data += '<div class="actkpimenu-item" data-id="0">&#12288;&nbsp;' + tableTitle[i].innerHTML + '&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;&#12288;▷</div>';
        //    }
        //    data += '</div>';
        //}
        //data += '</div>';
        actkpimenu.innerHTML = data;

        //根據鼠標右鍵位置定位
        if (e.pageX + 240 > actwidth) {
            actkpimenu.style.left = (actwidth - 260) + "px";
        } else {
            actkpimenu.style.left = e.pageX + "px";
        }
        if (e.pageY + 480 > actheight) {
            actkpimenu.style.top = (actheight - 480) + "px";
        } else {
            actkpimenu.style.top = e.pageY + "px";
        }
        //顯示菜單
        actkpimenu.style.display = "block";

        ////二級菜單
        //$("#monthInfo").mouseover(function (e) {
        //    $("#lv2").css({ "left": "230px", "top": "420px" });
        //    $("#lv2").show();
        //});
        //$("#monthInfo").mouseout(function (e) {
        //    $("#lv2").hide();
        //});
        ////三級菜單
        //for (var i = 16; i < 24; i++) {
        //    $("#info" + i).mouseover(function (e) {
        //        $("#lv3" + i).css({ "left": "230px", "top": "0px" });
        //        $("#lv3" + i).show();
        //    });
        //    $("#info" + i).mouseout(function (e) {
        //        $("#lv3" + i).hide();
        //    });
        //}
    }
    window.onclick = function (e) {
        //點擊（非右鍵菜單範圍）關閉
        if (e.target.className != "actkpimenu-item" && e.target.className != "actkpicheck-item") {
            actkpimenu.style.display = "none";
        }
    }
    window.onmousewheel = function (e) {
        //滑動滾輪關閉
        actkpimenu.style.display = "none";
    }
    //監聽菜單點擊
    window.addEventListener("click", function (e) {
        if (e.target.dataset.id) {
            actkpimenu.children[e.target.dataset.id - 3].children[0].checked = !actkpimenu.children[e.target.dataset.id - 3].children[0].checked;
            actkpiHideCol(e.target.dataset.id, actkpimenu.children[e.target.dataset.id - 3].children[0].checked);
        }
        //switch (e.target.dataset.id) {
        //    case "1": break;
        //}
    });
    //table列隱藏
    function actkpiHideCol(colIndex, event) {
        var checked;
        if (event == true || event == false) {
            checked = event;
        } else {
            checked = event.target.checked;
        }
        var thead = $("#KpiActDataTd table thead tr")[0].children;
        var tbody = $("#KpiActDataTd table tbody tr");
        //隱藏thead
        thead[colIndex].hidden = !checked;
        //隱藏tbody
        for (var i = 0; i < tbody.length; i += 3) {
            tbody[i].children[colIndex].hidden = !checked;
        }
    }
    //刷新數據後隱藏會失效，table每次渲染完後檢查一遍，若有失效則重新隱藏
    function reloadHide() {
        if (actkpimenu.innerHTML != '\n') {
            for (var j = 0; j < actkpimenu.children.length; j++) {
                actkpiHideCol(j + 3, actkpimenu.children[j].children[0].checked);
            }
        }
    }
</script>

@*界面主體*@
<div style="position: fixed; margin-top: -260px; background-color: white; width: 100%; z-index: 100;">
    <div style="border: 4px solid #92d050; width: 80%; height: 180px; margin: auto; margin-top: 20px; border-radius: 10px;">
        <table style="width: 100%; margin-top:10px;">
            <tr style="height:50px;">
                <td style="width: 10%; text-align: right;">域：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtContractAct" type="text" value="@ViewBag.Contract" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">年度：</td>
                <td style="width: 16%; text-align: left;">
                    @{
                        if (DateTime.Now.Month == 1)
                        {
                            <input id="TxtYearAct" type="text" value="@(DateTime.Now.Year - 1)" style="height:25px;width:162px;" />
                        }
                        else
                        {
                            <input id="TxtYearAct" type="text" value="@DateTime.Now.Year" style="height:25px;width:162px;" />
                        }
                    }
                </td>
                <td style="width: 10%; text-align: right;">月份：</td>
                <td style="width: 16%; text-align: left;">
                    @*<select id="TxtKpiMonthAct" aria-label="TxtKpiMonthAct" style="height:25px;width:162px;">
                            <option value=""></option>
                            @{
                                int month = DateTime.Now.Month;
                                for (int i = 1; i <= 12; i++)
                                {
                                    if (month - 1 == i || (month == 1 && i == 12))
                                    {
                                        <option value="@i" selected="selected">@i</option>
                                    }
                                    else
                                    {
                                        <option value="@i">@i</option>
                                    }
                                }
                            }
                        </select>*@
                    <div class="select_item provinces_region_box">
                        <select style="display: none;" id="TxtKpiMonthAct" aria-label="TxtKpiMonthAct" multiple placeholder="" name="" code="">
                        </select>
                    </div>
                </td>
            </tr>
            <tr>
                <td style="width: 10%; text-align: right;">NO：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtKpiNoAct" type="text" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">流程：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtKpiDescAct" type="text" style="height:25px;width:162px;" />
                </td>
                <td style="width: 10%; text-align: right;">績效指標：</td>
                <td style="width: 16%; text-align: left;">
                    <input id="TxtKpiTargetAct" type="text" style="height:25px;width:162px;" />
                </td>
            </tr>
            <tr style="height:50px;">
                <td style="width: 10%; text-align: right;">部門：</td>
                <td style="width: 16%; text-align: left;">
                    <select id="TxtKpiDeptAct" aria-label="TxtKpiDeptAct" style="height:25px;width:162px;">
                        <option value=""></option>
                        @{
                            foreach (System.Data.DataRow item in ViewBag.Dept)
                            {
                                <option value="@item["DEPT_ID"].ToString()">@item["DEPT_DESC"].ToString()</option>
                            }
                        }
                    </select>
                </td>
                <td style="width: 10%; text-align: right;">衡量頻率：</td>
                <td style="width: 16%; text-align: left;">
                    <select id="TxtKpiFreqAct" aria-label="TxtKpiFreqAct" style="height:25px;width:162px;">
                        <option value=""></option>
                        @{
                            foreach (System.Data.DataRow item in ViewBag.Freq)
                            {
                                <option value="@item["CONF_ID"].ToString()">@item["CONF_NM"].ToString()</option>
                            }
                        }
                    </select>
                </td>
                <td style="width: 10%; text-align: right;">輸入方式：</td>
                <td style="width: 16%; text-align: left;">
                    <select id="TxtKpiInputAct" aria-label="TxtKpiInputAct" style="height:25px;width:162px;">
                        <option value=""></option>
                        @{
                            foreach (System.Data.DataRow item in ViewBag.Input)
                            {
                                <option value="@item["CONF_ID"].ToString()">@item["CONF_NM"].ToString()</option>
                            }
                        }
                    </select>
                </td>
                @*<td style="width: 10%; text-align: right;">週期類別：</td>
                    <td style="width: 16%; text-align: left;">
                        <select id="TxtKpiPeriodAct" style="height:25px;width:162px;">
                            <option value=""></option>
                            @{
                                foreach (System.Data.DataRow item in ViewBag.Period)
                                {
                                    <option value="@item["CONF_NM"].ToString()">@item["CONF_V2"].ToString()</option>
                                }
                            }
                        </select>
                    </td>*@
            </tr>
            <tr>
                <td style="width: 10%; text-align: right;">判定(填寫月份)：</td>
                <td style="width: 16%; text-align: left;">
                    <select id="TxtKpiResultAct" aria-label="TxtKpiResultAct" style="height:25px;width:162px;">
                        <option value=""></option>
                        @{
                            foreach (System.Data.DataRow item in ViewBag.Result)
                            {
                                <option value="@item["CONF_NM"].ToString()">@item["CONF_DESC"].ToString()</option>
                            }
                        }
                    </select>
                </td>
                <td></td>
                <td></td>
                <td></td>
                <td>
                    <select id="TxtKpiReportSel" aria-label="TxtKpiReportSel" style="height:25px;width:100px;">
                        <option value="1">匯總表</option>
                        <option value="2">差異分析表</option>
                    </select>
                    <input id="BtnReportDataAct" type="button" value="導出" style="width: 58px; height: 25px;" onclick="ReportDataAct()" />
                </td>
            </tr>
        </table>
    </div>
    <div style="text-align: left; margin-top: 15px; margin-left:15%; width: 80%; height: 40px;">
        <input id="BtnKpiSearchAct" type="button" value="查&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;詢" style="width: 100px; height: 25px;" onclick="btnKpiSearchClickAct('FP')" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <input id="BtnKpiSaveAct" type="button" value="保&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;存" style="width: 100px; height: 25px;" onclick="saveKpiDataAct()" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        @{
            if (Session["PERMISSIONS"].ToString() == "1")
            {
                <input id="BtnKpiCloseAct" type="button" value="QA鎖定/取消" style="width: 100px; height: 25px;" onclick="btnKpiLockClickAct()" />
                <span id="kpilockact" style="color:red;"></span>
                <input id="BtnKpiFlowIniAct" type="button" value="啟動Flow簽核" style="width: 100px; height: 25px;" onclick="BtnKpiFlowIniActClick()" />
                <input id="OthMonth" type="text" style="height:25px;width:50px;" />
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                <input id="BtnEditOth" type="button" value="編輯其他月份" style="width:100px; height:25px;" onclick="editOth()" />
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
                @*<input id="BtnReportDataActFailed" type="button" value="導出差異分析表" style="width: 100px; height: 25px;" onclick="ReportDataAct(true)" />
                <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>*@
            }
        }
        @*<input id="BtnReportDataAct" type="button" value="導出數據" style="width: 100px; height: 25px;" onclick="ReportDataAct(false)" />*@
        <input id="BtnKpiCloseAct" type="button" value="確定/取消" style="width: 100px; height: 25px;" onclick="btnKpiCloseClickAct()" hidden="hidden" />
    </div>
</div>
<div id="KpiActDataTdP" style="text-align: center; margin-top: 260px; margin-left: 2%; width: 96%; overflow: auto; border-radius: 5px; z-index: 99;">
    @{          
        System.Data.DataTable kpiActData = ViewBag.KpiActData;
        System.Data.DataTable kpiActDataGroup = ViewBag.KpiActDataGroup;
        System.Data.DataTable kpiLastYearDe = ViewBag.KpiLastYearDe;
        string vb_month = ViewBag.Month;
        if (kpiActData.Rows.Count == 0)
        {
            ViewBag.TdWidth = "100%";
            ViewBag.TdHeigth = "500px";
        }
        else
        {
            ViewBag.TdHeigth = "580px";
        }
        <div id="KpiActDataTd" style="text-align: center; width: @ViewBag.TdWidth; height:@ViewBag.TdHeigth;">
            @{
                if (kpiActData.Rows.Count > 0)
                {
                    <table style="width: 100%; border-left: 1px solid #507cd1; border-right: 1px solid #507cd1;">
                        <thead style="position:sticky;top:0;">
                            <tr style="background-color: #507cd1; font-size: 18px; color: white; font-weight: bold; height: 40px;">
                                <td hidden="hidden">KPI_ID</td>
                                <td hidden="hidden">PERIOD_TYPE</td>
                                <td width="60"><input id="kpititlecheck" type="checkbox" aria-label="kpititlecheck" onchange="kpititelcheckChange(event)" /></td>
                                @*<td width="80">域</td>*@
                                <td width="60">年度</td>
                                <td width="60">NO</td>
                                <td width="150">流程</td>
                                <td width="150">績效指標</td>
                                <td width="150">公式</td>
                                <td width="60">輸入<br />方式</td>
                                <td width="60">衡量<br />頻率</td>
                                <td width="60">數值<br />形式</td>
                                <td width="80">數值<br />趨勢</td>
                                @*<td width="60">週期<br />類別</td>*@
                                <td width="80">流程<br />負責人</td>
                                <td width="60">年度</td>
                                <td width="60">年度<br />結果</td>
                                <td width="60">未達標<br />次數</td>
                                <td width="80"></td>
                                @{
                                    //月份篩選
                                    <!--if (vb_month == "1")
                                    {
                                        <td>上年度12月</td>-->
                                        @*<td>狀態</td>*@
                                        <!--<td>差異分析</td>
                                        <td>改善措施</td>
                                        <td>ECD</td>
                                        <td>備註</td>
                                    }-->
                                    for (int i = 1; i <= 12; i++)
                                    {
                                        if (vb_month.IndexOf(',') >= 0 && !vb_month.Split(',').Contains(i.ToString()))
                                        {
                                            //多選
                                            continue;
                                        }
                                        else
                                        {
                                            //單選
                                            if (/*!vb_month.Split(',').Contains((i + 1).ToString()) && */!vb_month.Split(',').Contains(i.ToString()) && vb_month != "0")
                                            {
                                                continue;
                                            }
                                        }
                                        <td>@(i)月</td>
                                        @*<td>狀態</td>*@
                                        <td>差異分析</td>
                                        <td>改善措施</td>
                                        <td>ECD</td>
                                        <td>備註</td>
                                        <td hidden="hidden">PERIOD_VALUE</td>
                                    }
                                }
                            </tr>
                        </thead>
                        <tbody>
                            @{
                                int colorIndex = 1;
                                string color;
                                string result_color;
                                //string kpi_result;
                                //string kpi_valueact;
                                int now_month = DateTime.Now.Month;
                                int now_year = DateTime.Now.Year;
                                System.Data.DataRow[] dataRows;
                                System.Data.DataRow[] dataRowsDe;
                                foreach (System.Data.DataRow item in kpiActDataGroup.Rows)
                                {
                                    color = colorIndex % 2 == 1 ? "#eff3fb" : "#ffffff";
                                    for (int j = 1; j <= 3; j++)
                                    {
                                        <tr class="kpiacttr" style="background-color:@color; height: 35px;">
                                            @{
                                                if (j == 1)
                                                {
                                                    <td rowspan="3" hidden="hidden">@item["KPI_ID"].ToString()</td>
                                                    <td rowspan="3" hidden="hidden">@item["PERIOD_TYPE"].ToString()</td>
                                                    <td rowspan="3"><input type="checkbox" class="kpiactdatacheck" aria-label="kpiactdatacheck" onchange="kpidatacheckChange(event)" /></td>
                                                    @*<td style="border: 1px solid #507cd1;" rowspan="3">@item["SITE"].ToString()</td>*@
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["KPI_YEAR"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["KPI_NO"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["KPI_DESC"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["KPI_TARGET"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["KPI_FUNC"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["INPUT_TYPE"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["FREQ_DESC"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["V_FORM_DESC"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["TREND_DESC"].ToString()</td>
                                                    @*<td style="border: 1px solid #507cd1;" rowspan="3">@item["CONF_V2"].ToString()</td>*@
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["KPI_OWNER"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["YEARLY_TYPE"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["YEARLY_RESULT"].ToString()</td>
                                                    <td style="border: 1px solid #507cd1;" rowspan="3">@item["UNQTY"].ToString()</td>
                                                }

                                                int colNum = 1;
                                                int tdNum = 0;
                                                if (item["PERIOD_TYPE"].ToString() == "M")
                                                {
                                                    tdNum = 0;
                                                    colNum = 1;
                                                }
                                                else if (item["PERIOD_TYPE"].ToString() == "Q")
                                                {
                                                    tdNum = 8;
                                                    colNum = 3;
                                                }
                                                else if (item["PERIOD_TYPE"].ToString() == "H")
                                                {
                                                    tdNum = 20;
                                                    colNum = 6;
                                                }
                                                else if (item["PERIOD_TYPE"].ToString() == "Y")
                                                {
                                                    tdNum = 44;
                                                    colNum = 12;
                                                }
                                                dataRows = kpiActData.Select("KPI_ID=" + item["KPI_ID"].ToString() + " AND SITE='" + item["SITE"].ToString() + "' AND KPI_YEAR=" + item["KPI_YEAR"].ToString() + " AND KPI_NO=" + item["KPI_NO"].ToString() + " AND PERIOD_TYPE='" + item["PERIOD_TYPE"].ToString() + "'");
                                                for (int i = 1; i <= dataRows.Count(); i++)
                                                {
                                                    //行標題
                                                    if (i == 1 && j == 1)
                                                    {
                                                        <td>Target</td>
                                                        if (vb_month != "0" && item["PERIOD_TYPE"].ToString() != "M")
                                                        {
                                                            <td rowspan="3"></td>
                                                            <td rowspan="3"></td>
                                                            <td rowspan="3"></td>
                                                            <td rowspan="3"></td>
                                                        }
                                                    }
                                                    else if (i == 1 && j == 2)
                                                    {
                                                        <td>Actual</td>
                                                    }
                                                    else if (i == 1 && j == 3)
                                                    {
                                                        <td>判定</td>
                                                    }
                                                    //月份篩選
                                                    //一月份跨年處理
                                                    <!--if (vb_month == "1" && i == 1)
                                                    {
                                                        dataRowsDe = kpiLastYearDe.Select("KPI_ID=" + item["KPI_ID"].ToString() + " AND SITE='" + item["SITE"].ToString() + "' AND KPI_NO=" + item["KPI_NO"].ToString() + " AND PERIOD_TYPE='" + item["PERIOD_TYPE"].ToString() + "'");
                                                        if (j == 1)
                                                        {
                                                            @*<td>@(dataRowsDe.Count() == 0 ? "" : dataRowsDe[1]["KPI_V2"].ToString())</td>-->*@
                                                            @*@*<td rowspan="3">@(dataRowsDe.Count() ==0 ? "" : dataRowsDe[0]["STATUS_E"].ToString())</td>*@
                                                            @*<!--<td rowspan="3"><textarea rows="4" style="width:@ViewBag.TaWidth;" disabled="disabled">@(dataRowsDe.Count() == 0 ? "" : dataRowsDe[1]["DIFF_ANALYSIS"].ToString())</textarea></td>*@
                                                            @*<td rowspan="3"><textarea rows="4" style="width:@ViewBag.TaWidth;" disabled="disabled">@(dataRowsDe.Count() == 0 ? "" : dataRowsDe[1]["IMPROVE_MEASURE"].ToString())</textarea></td>*@
                                                            @*<td rowspan="3"><input type="date" value="@(dataRowsDe.Count() == 0 ? "" : dataRowsDe[0]["ECD"].ToString())" style="width:100px;" disabled="disabled" /></td>*@
                                                        }
                                                        else if (j == 2)
                                                        {
                                                            if (dataRowsDe.Count() > 0)
                                                            {
                                                                if (dataRowsDe[1]["KPI_RESULT"].ToString() == "1")
                                                                {
                                                                    //合格，綠色
                                                                    result_color = "#c6efce";
                                                                }
                                                                else if (dataRowsDe[1]["KPI_RESULT"].ToString() == "2")
                                                                {
                                                                    //不合格
                                                                    if (dataRowsDe[0]["KPI_RESULT"].ToString() == "2")
                                                                    {
                                                                        if ((dataRowsDe[1]["TREND_DESC"].ToString() == "越大越好" && Convert.ToInt32(dataRowsDe[1]["KPI_VALUEACT"]) > Convert.ToInt32(dataRowsDe[0]["KPI_VALUEACT"])) || (dataRowsDe[1].ToString() == "越小越好" && Convert.ToInt32(dataRowsDe[1]["KPI_VALUEACT"]) < Convert.ToInt32(dataRowsDe[0]["KPI_VALUEACT"])))
                                                                        {
                                                                            //較上月有進步，黃色
                                                                            result_color = "#ffeb9c";
                                                                        }
                                                                        else
                                                                        {
                                                                            //較上月無進步，紅色
                                                                            result_color = "#ffc7ce";
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        //上月合格本月不合格，紅色
                                                                        result_color = "#ffc7ce";
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    result_color = "none";
                                                                }
                                                            }
                                                            else
                                                            {
                                                                result_color = "none";
                                                            }
                                                            @*<td><input type="text" value="@(dataRowsDe.Count() == 0 ? "" : dataRowsDe[1]["KPI_VALUEACT"].ToString())" style="width: 50px; height: 25px; background-color: @result_color;" disabled="disabled" /></td>*@
                                                        }
                                                        else if (j == 3)
                                                        {
                                                            if (dataRowsDe.Count() == 0)
                                                            {
                                                                <td></td>
                                                            }
                                                            else
                                                            {
                                                                @*<td>@dataRowsDe[1]["KPI_RESULT_V"].ToString()</td>*@
                                                            }
                                                        }
                                                    }-->
                                                    if (vb_month.IndexOf(',') >= 0 && !vb_month.Split(',').Contains((i * colNum).ToString()) && vb_month != "0")
                                                    {
                                                        continue;
                                                    }
                                                    else if (vb_month.IndexOf(',') < 0 && !vb_month.Split(',').Contains((i * colNum).ToString()) /*&& !vb_month.Split(',').Contains((i * colNum + 1).ToString())*/ && vb_month != "0")
                                                    {
                                                        continue;
                                                    }
                                                    if (vb_month != "0")
                                                    {
                                                        if (vb_month.IndexOf(',') >= 0 && !vb_month.Split(',').Contains((i * colNum).ToString()))
                                                        {
                                                            <td></td>
                                                            <td></td>
                                                            <td></td>
                                                            <td></td>
                                                        }
                                                        else if (vb_month.IndexOf(',') < 0 && !vb_month.Split(',').Contains((i * colNum).ToString()) /*&& !vb_month.Split(',').Contains((i * colNum + 1).ToString())*/)
                                                        {
                                                            <td></td>
                                                            <td></td>
                                                            <td></td>
                                                            <td></td>
                                                        }
                                                    }
                                                    else
                                                    {
                                                        for (int t = 0; t < tdNum; t++)
                                                        {
                                                            <td></td>
                                                        }
                                                    }
                                                    //行內容
                                                    if (j == 1)
                                                    {
                                                        <td>@dataRows[i - 1]["KPI_V2"].ToString()</td>
                                                        if (dataRows[i - 1]["IS_LOCK"].ToString() == "N" && (Convert.ToInt32(item["KPI_YEAR"]) == now_year || (Convert.ToInt32(item["KPI_YEAR"]) == now_year - 1 && i * colNum == 12 && now_month == 1)) && (i * colNum == now_month - 1 || (i * colNum == 12 && now_month == 1)))
                                                        {
                                                            @*<td rowspan="3">@dataRows[i - 1]["STATUS_E"].ToString()</td>*@
                                                            <td rowspan="3"><textarea rows="5" style="width:@ViewBag.TaWidth;" onchange="isChange(event)">@dataRows[i - 1]["DIFF_ANALYSIS"].ToString()</textarea></td>
                                                            <td rowspan="3"><textarea rows="5" style="width:@ViewBag.TaWidth;" onchange="isChange(event)">@dataRows[i - 1]["IMPROVE_MEASURE"].ToString()</textarea></td>
                                                            <td rowspan="3"><input type="date" value="@dataRows[i - 1]["ECD"].ToString()" style="width:100px;" onchange="isChange(event)" /></td>
                                                            <td rowspan="3"><textarea rows="5" style="width:@ViewBag.TaWidth;" onchange="isChange(event)">@dataRows[i - 1]["REMARK"].ToString()</textarea></td>
                                                            <td rowspan="3" hidden="hidden">@dataRows[i - 1]["PERIOD_VALUE"].ToString()</td>
                                                        }
                                                        else
                                                        {
                                                            @*<td rowspan="3">@dataRows[i - 1]["STATUS_E"].ToString()</td>*@
                                                            <td rowspan="3"><textarea rows="5" style="width:@ViewBag.TaWidth;" onchange="isChange(event)" disabled="disabled">@dataRows[i - 1]["DIFF_ANALYSIS"].ToString()</textarea></td>
                                                            <td rowspan="3"><textarea rows="5" style="width:@ViewBag.TaWidth;" onchange="isChange(event)" disabled="disabled">@dataRows[i - 1]["IMPROVE_MEASURE"].ToString()</textarea></td>
                                                            <td rowspan="3"><input type="date" value="@dataRows[i - 1]["ECD"].ToString()" style="width:100px;" onchange="isChange(event)" disabled="disabled" /></td>
                                                            <td rowspan="3"><textarea rows="5" style="width:@ViewBag.TaWidth;" onchange="isChange(event)" disabled="disabled">@dataRows[i - 1]["REMARK"].ToString()</textarea></td>
                                                            <td rowspan="3" hidden="hidden">@dataRows[i - 1]["PERIOD_VALUE"].ToString()</td>
                                                        }
                                                    }
                                                    else if (j == 2)
                                                    {
                                                        //if (dataRows[i - 1]["KPI_RESULT"].ToString() == "1")
                                                        //{
                                                        //    //合格，綠色
                                                        //    result_color = "#c6efce";
                                                        //}
                                                        //else if (dataRows[i - 1]["KPI_RESULT"].ToString() == "2")
                                                        //{
                                                        //    if (vb_month == "1" || (vb_month == "0" && i == 1))
                                                        //    {
                                                        //        dataRowsDe = kpiLastYearDe.Select("KPI_ID=" + item["KPI_ID"].ToString() + " AND SITE='" + item["SITE"].ToString() + "' AND KPI_NO=" + item["KPI_NO"].ToString() + " AND PERIOD_TYPE='" + item["PERIOD_TYPE"].ToString() + "'");
                                                        //        if (dataRowsDe.Count() != 0)
                                                        //        {
                                                        //            kpi_result = dataRowsDe[1]["KPI_RESULT"].ToString();
                                                        //            kpi_valueact = dataRowsDe[1]["KPI_VALUEACT"].ToString();
                                                        //        }
                                                        //        else
                                                        //        {
                                                        //            kpi_result = "";
                                                        //            kpi_valueact = "0";
                                                        //        }
                                                        //    }
                                                        //    else
                                                        //    {
                                                        //        kpi_result = dataRows[i - 2]["KPI_RESULT"].ToString();
                                                        //        kpi_valueact = dataRows[i - 2]["KPI_VALUEACT"].ToString();
                                                        //    }
                                                        //    //不合格
                                                        //    if (kpi_result == "2")
                                                        //    {
                                                        //        if ((dataRows[i - 1]["TREND_DESC"].ToString() == "越大越好" && Convert.ToInt32(dataRows[i - 1]["KPI_VALUEACT"]) > Convert.ToInt32(kpi_valueact)) || (dataRows[i - 1]["TREND_DESC"].ToString() == "越小越好" && Convert.ToInt32(dataRows[i - 1]["KPI_VALUEACT"]) < Convert.ToInt32(kpi_valueact)))
                                                        //        {
                                                        //            //較上月有進步，黃色
                                                        //            result_color = "#ffeb9c";
                                                        //        }
                                                        //        else
                                                        //        {
                                                        //            //較上月無進步，紅色
                                                        //            result_color = "#ffc7ce";
                                                        //        }
                                                        //    }
                                                        //    else
                                                        //    {
                                                        //        //上月合格本月不合格，紅色
                                                        //        result_color = "#ffc7ce";
                                                        //    }
                                                        //}
                                                        //else
                                                        //{
                                                        //    result_color = "none";
                                                        //}
                                                        if (dataRows[i - 1]["RESULT_COLOR"].ToString() == "GREEN")
                                                        {
                                                            result_color = "#c6efce";
                                                        }
                                                        else if (dataRows[i - 1]["RESULT_COLOR"].ToString() == "RED")
                                                        {
                                                            result_color = "#ffc7ce";
                                                        }
                                                        else if (dataRows[i - 1]["RESULT_COLOR"].ToString() == "YELLOW")
                                                        {
                                                            result_color = "#ffeb9c";
                                                        }
                                                        else if (dataRows[i - 1]["RESULT_COLOR"].ToString() == "BLANK")
                                                        {
                                                            result_color = "none";
                                                        }
                                                        else
                                                        {
                                                            result_color = "none";
                                                        }
                                                        if (dataRows[i - 1]["IS_LOCK"].ToString() == "N" && (Convert.ToInt32(item["KPI_YEAR"]) == now_year || (Convert.ToInt32(item["KPI_YEAR"]) == now_year - 1 && i * colNum == 12 && now_month == 1)) && (i * colNum == now_month - 1 || (i * colNum == 12 && now_month == 1)))
                                                        {
                                                            <td><input type="text" value="@dataRows[i - 1]["KPI_VALUEACT"].ToString()" style="width: 50px; height: 25px; background-color: @result_color;" onchange="isChange(event)" /></td>
                                                        }
                                                        else
                                                        {
                                                            <td><input type="text" value="@dataRows[i - 1]["KPI_VALUEACT"].ToString()" style="width: 50px; height: 25px; background-color: @result_color;" onchange="isChange(event)" disabled="disabled" /></td>
                                                        }
                                                    }
                                                    else if (j == 3)
                                                    {
                                                        <td>@dataRows[i - 1]["KPI_RESULT_V"].ToString()</td>
                                                    }
                                                }
                                            }
                                        </tr>
                                    }
                                    colorIndex++;
                                }
                            }
                        </tbody>
                        <tfoot>
                            <tr style="background-color:#507cd1; font-size:15px; color: white; height:35px;">
                                <td colspan="20" style="text-align: left; position: sticky; bottom: 0; left: 0; z-index: 2; background-color: #507cd1;">
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    第:
                                    <span id="pagesIndex">@ViewBag.PagesIndex</span>
                                    頁/共:
                                    <span>@ViewBag.PagesCount</span>
                                    頁
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClickAct('FP')">首頁</a>
                                    <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClickAct('PP')">上一頁</a>
                                    <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClickAct('NP')">下一頁</a>
                                    <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClickAct('LP')">尾頁</a>
                                    轉到第
                                    <input id="pagesTo" type="number" value="@ViewBag.PagesIndex" style="height:20px;width:40px;color:black;" />
                                    頁
                                    <a style="cursor:pointer;color:white;" onclick="btnKpiSearchClickAct('TP')">Go</a>
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    每頁
                                    <select id="pagesNum" style="height: 20px; width: 40px; color: black;" onchange="btnKpiSearchClickAct('FP')">
                                        @{
                                            int value = 0;
                                            for (int i = 1; i <= 5; i++)
                                            {
                                                value = i * 10;
                                                if (ViewBag.pagesNum == i * 10)
                                                {
                                                    <option value="@value" selected="selected">@value</option>
                                                }
                                                else
                                                {
                                                    <option value="@value">@value</option>
                                                }
                                            }
                                        }
                                    </select>
                                    筆/共
                                    <span>@ViewBag.DataNums</span>
                                    筆
                                    &nbsp;&nbsp;&nbsp;
                                </td>
                                <td colspan="@ViewBag.TfCs" style="text-align: left; position: sticky; bottom: 0; right: 0; z-index: 1; background-color: #507cd1;"></td>
                            </tr>
                        </tfoot>
                    </table>
                }
                else
                {
                    <h3 style="margin-top:100px;">未查詢到數據！</h3>
                }
            }
        </div>
    }
</div>

<script>
    //更新鎖定狀態
    function updateLockInfo() {
        //var site = $("#TxtContractAct").val();
        //var year = $("#TxtYearAct").val();
        //var site = "EMCHS"
        var year = new Date().getFullYear();
        var month = new Date().getMonth();
        if (month == 0) {
            year--;
            month = "12";
        } else {
            month = month.toString().padStart(2, "0");
        }
        $.ajax({
            type: "post",
            url: "/Kpi/IsLockSpanAct",
            data: {
                //site: site,
                year: year,
                month: month
            },
            success: function (data) {
                var result = JSON.parse(data);
                if (result.flag) {
                    $("#kpilockact")[0].innerHTML = result.isLock;
                } else {
                    alert(result.msg);
                }
            }
        });
    }
    //查詢
    function btnKpiSearchClickAct(flipPage) {
        //console.log(sel_data);
        showLoading();
        $.ajax({
            type: "get",
            url: "/Kpi/BtnSearchClickAct",
            data: {
                txtKpiSite: $("#TxtContractAct").val(),
                txtKpiYear: $("#TxtYearAct").val(),
                txtKpiNo: $("#TxtKpiNoAct").val(),
                txtKpiDesc: $("#TxtKpiDescAct").val(),
                txtKpiTarget: $("#TxtKpiTargetAct").val(),
                txtKpiDept: $("#TxtKpiDeptAct").val(),
                //txtKpiPeriod: $("#TxtKpiPeriodAct").val(),
                txtKpiPeriod: "M",
                txtKpiFreq: $("#TxtKpiFreqAct").val(),
                txtKpiMonth: sel_data,
                txtKpiInput: $("#TxtKpiInputAct").val(),
                txtKpiResult: $("#TxtKpiResultAct").val(),
                pagesIndex: $("#pagesIndex").text(),
                pagesNum: $("#pagesNum").val(),
                pagesTo: $("#pagesTo").val(),
                flipPage: flipPage
            },
            success: function (data) {
                updateLockInfo();
                $("#KpiActDataTdP").html(data);
                tableRowSpan(6, 7);
                reloadHide();
                hideLoading();
            },
            error: function (err) {
                hideLoading();
            }
        });
    }
    //保存
    function saveKpiDataAct() {
        var updateData = [];
        var updateDataOth = [];
        var kpiActDataTd = $("#KpiActDataTd tbody tr");
        var KPI_ID;
        var PERIOD_TYPE;
        var PERIOD_VALUE;
        //var PERIOD_VALUE2;
        var KPI_VALUEACT;
        var DIFF_ANALYSIS;
        var IMPROVE_MEASURE;
        var ECD;
        var REMARK;
        var changeFlag1;
        var changeFlag2;
        var changeFlag3;
        var changeFlag4;
        var changeFlag5;

        var monthNow = new Date().getMonth();
        monthNow = monthNow == 0 ? 12 : monthNow;
        var ftimes = sel_data.split(',').length;
        ftimes = sel_data == "0" ? 12 : ftimes;
        var mindex = sel_data.split(',').indexOf(monthNow.toString()) + 1;
        mindex = sel_data == "0" ? monthNow : mindex;
        if (ftimes == 1 && mindex == 1) {
            mindex = 1;
        } else if (ftimes == 1 && mindex == 0) {
            mindex = 1;
        }
        //ftimes = ftimes == 1 ? 2 : ftimes;
        for (var i = 0; i < kpiActDataTd.length; i += 3) {
            //選中勾選框
            if (kpiActDataTd[i].cells[2].children[0].checked) {
                for (var m = 1; m <= ftimes; m++) {
                    if (m > mindex) {
                        continue;
                    }
                    KPI_ID = kpiActDataTd[i].cells[0].innerText;
                    PERIOD_TYPE = kpiActDataTd[i].cells[1].innerText;
                    //if (kpiActDataTd[i].cells[1].innerHTML == "M") {
                    //    PERIOD_VALUE = monthNow.toString().padStart(2, '0');
                    //} else {
                    //    PERIOD_VALUE = monthNow.toString();
                    //}
                    KPI_VALUEACT = kpiActDataTd[i + 1].cells[m].children[0].value;
                    changeFlag1 = kpiActDataTd[i + 1].cells[m].children[0].isChange;
                    if ((isNaN(KPI_VALUEACT) || parseInt(KPI_VALUEACT) < 0) && KPI_VALUEACT != "NA") {
                        alert("輸入錯誤，實際達成值應為大於零的數值或NA！");
                        return;
                    }
                    if (KPI_VALUEACT == "NA") {
                        KPI_VALUEACT = "-1";
                    }
                    DIFF_ANALYSIS = kpiActDataTd[i].cells[12 + m * 6].children[0].value;
                    changeFlag2 = kpiActDataTd[i].cells[12 + m * 6].children[0].isChange;
                    IMPROVE_MEASURE = kpiActDataTd[i].cells[13 + m * 6].children[0].value;
                    changeFlag3 = kpiActDataTd[i].cells[13 + m * 6].children[0].isChange;
                    ECD = kpiActDataTd[i].cells[14 + m * 6].children[0].value;
                    changeFlag4 = kpiActDataTd[i].cells[14 + m * 6].children[0].isChange;
                    REMARK = kpiActDataTd[i].cells[15 + m * 6].children[0].value;
                    changeFlag5 = kpiActDataTd[i].cells[15 + m * 6].children[0].isChange;
                    PERIOD_VALUE = kpiActDataTd[i].cells[16 + m * 6].innerText;
                    if (DIFF_ANALYSIS == "" || IMPROVE_MEASURE == "" || ECD == "") {
                        if (!(DIFF_ANALYSIS == "" && IMPROVE_MEASURE == "" && ECD == "")) {
                            alert("差異分析、改善措施、ECD應都為空或都有值！");
                            return;
                        }
                    }
                    if (monthNow != parseInt(PERIOD_VALUE) && editOthFlag && (changeFlag1 || changeFlag2 || changeFlag3 || changeFlag4 || changeFlag5)) {
                        updateDataOth.push(KPI_ID + "§" + PERIOD_TYPE + "§" + PERIOD_VALUE + "§" + KPI_VALUEACT + "§" + DIFF_ANALYSIS + "§" + IMPROVE_MEASURE + "§" + ECD + "§" + REMARK);
                    }
                    if (monthNow == parseInt(PERIOD_VALUE) && !editOthFlag && (changeFlag1 || changeFlag2 || changeFlag3 || changeFlag4 || changeFlag5)) {
                        updateData.push(KPI_ID + "§" + PERIOD_TYPE + "§" + PERIOD_VALUE + "§" + KPI_VALUEACT + "§" + DIFF_ANALYSIS + "§" + IMPROVE_MEASURE + "§" + ECD + "§" + REMARK);
                    }
                }
            }
        }
        if (updateData.length == 0 && updateDataOth.length == 0) {
            alert("沒有數據需要保存！（請先選中首欄勾選框，並輸入數據後保存）");
            return;
        }
        showLoading();
        $.ajax({
            type: "post",
            url: "/Kpi/BtnKpiSaveClickAct",
            data: {
                updateData: updateData.join('⊕'),
                updateDataOth: updateDataOth.join('⊕'),
                editOthFlag: editOthFlag
            },
            success: function (data) {
                hideLoading();
                var result = JSON.parse(data);
                if (result.flag) {
                    alert(result.msg);
                    btnKpiSearchClickAct('CP');
                } else {
                    alert(result.msg);
                }
            },
            error: function (err) {
                hideLoading();
            }
        });
    }
    //關閉/取消
    function btnKpiCloseClickAct() {
        var updateData = [];
        var month = $("#TxtKpiMonthAct").val();
        month = month == "" || month == null ? 0 : Number(month);
        var editMonth;
        var mIndex;
        var KPI_ID;
        var PERIOD_TYPE;
        var PERIOD_VALUE;
        var kpiDataTd = $("#KpiActDataTd tbody tr");
        for (var i = 0; i < kpiDataTd.length; i += 3) {
            if (kpiDataTd[i].cells[2].children[0].checked) {
                if (kpiDataTd[i].cells[1].innerHTML == "M") {
                    editMonth = "1,2,3,4,5,6,7,8,9,10,11,12";
                    mIndex = 1;
                } else if (kpiDataTd[i].cells[1].innerHTML == "Q") {
                    editMonth = "3,6,9,12";
                    mIndex = 3;
                } else if (kpiDataTd[i].cells[1].innerHTML == "H") {
                    editMonth = "6,12";
                    mIndex = 6;
                } else if (kpiDataTd[i].cells[1].innerHTML == "Y") {
                    editMonth = "12";
                    mIndex = 12;
                }
                if (kpiDataTd[i].cells[1].innerHTML == "M") {
                    KPI_ID = kpiDataTd[i].cells[0].innerText;
                    PERIOD_TYPE = kpiDataTd[i].cells[1].innerText;
                    PERIOD_VALUE = month.toString().padStart(2, '0');
                    updateData.push(KPI_ID + "^" + PERIOD_TYPE + "^" + PERIOD_VALUE);
                } else {
                    if (new Date().getMonth() + 1 == month && editMonth.indexOf(month) >= 0) {
                        KPI_ID = kpiDataTd[i].cells[0].innerText;
                        PERIOD_TYPE = kpiDataTd[i].cells[1].innerText;
                        PERIOD_VALUE = (month / mIndex).toString();
                        updateData.push(KPI_ID + "^" + PERIOD_TYPE + "^" + PERIOD_VALUE);
                    }
                }
            }
        }
        if (updateData.length == 0) {
            alert("請選擇至少一條數據！");
            return;
        }
        if (confirm("確認變更當月狀態？")) {
            //關閉則打開，未關閉則關閉
            showLoading();
            $.ajax({
                type: "post",
                url: "/Kpi/KpiCloseOrCancelAct",
                data: {
                    //site: "EMCHS",
                    data: updateData.join('&')
                },
                success: function (data) {
                    hideLoading();
                    var result = JSON.parse(data);
                    if (result.flag) {
                        alert(result.msg);
                        btnKpiSearchClickAct('FP');
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (err) {
                    hideLoading();
                }
            });
        }
    }
    //鎖定/取消
    function btnKpiLockClickAct() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth();
        if (month == 0) {
            year--;
            month = "12";
        } else {
            month = month.toString().padStart(2, "0");
        }
        //查詢是否鎖定
        showLoading();
        $.ajax({
            type: "post",
            url: "/Kpi/IsLockAct",
            data: {
                //site: "EMCHS",
                year: year,
                month: month
            },
            success: function (data) {
                hideLoading();
                var result = JSON.parse(data);
                if (result.flag) {
                    var prompt = "確認鎖定[" + year + "-" + month + "]KPI實際？";
                    if (result.isLock) {
                        prompt = "[" + year + "-" + month + "]KPI實際已鎖定，確認打開？";
                    }
                    if (confirm(prompt)) {
                        //鎖定則打開，未鎖定則鎖定
                        showLoading();
                        $.ajax({
                            type: "post",
                            url: "/Kpi/KpiLockOrCancelAct",
                            data: {
                                //site: "EMCHS",
                                year: year,
                                month: month,
                                flag: result.isLock ? "lock" : "cancel"
                            },
                            success: function (data) {
                                hideLoading();
                                var result = JSON.parse(data);
                                if (result.flag) {
                                    alert(result.msg);
                                    updateLockInfo();
                                    btnKpiSearchClickAct('FP');
                                } else {
                                    alert(result.msg);
                                }
                            },
                            error: function (err) {
                                hideLoading();
                            }
                        });
                    } else {

                    }
                } else {
                    alert(result.msg);
                }
            },
            error: function (err) {
                hideLoading();
            }
        });
    }

    //輸入日期驗證
    function isSixDigitDateMonth(input) {
        const str = String(input);

        // 格式检查：必须为6位纯数字
        if (!/^\d{6}$/.test(str)) {
            return false;
        }

        // 拆分年份和月份
        const yearPart = str.substring(0, 4);  // 前4位为年份
        const monthPart = str.substring(4);    // 后2位为月份

        // 转换为数值
        const year = parseInt(yearPart, 10);
        const month = parseInt(monthPart, 10);

        // 验证年份有效性（1~9999）
        const isYearValid = year >= 2000 && year <= 3000;

        // 验证月份有效性（1~12）
        const isMonthValid = month >= 1 && month <= 12;

        return isYearValid && isMonthValid;
    }
    //啟動Flow簽核
    function BtnKpiFlowIniActClick() {
        var oth_flag = false;
        var lock = $("#kpilockact")[0].innerHTML;
        var kpi_month;
        if (new Date().getMonth() == 0) {
            kpi_month = (new Date().getFullYear() - 1) + "12";
        } else {
            kpi_month = new Date().getFullYear().toString() + new Date().getMonth().toString().padStart(2, '0');
        }

        var oth_month = $("#OthMonth").val();
        if (oth_month != "" && oth_month != null) {
            if (!isSixDigitDateMonth(oth_month)) {
                alert("請輸入正確且適當的日期數據。（YYYYMM）");
                $("#OthMonth").val("");
                return;
            }
            if (oth_month == kpi_month) {
                if (lock.indexOf("未鎖定") > 0) {
                    alert("未鎖定，無法啟動簽核");
                    return;
                }
            }
            if (parseInt(oth_month) > parseInt(kpi_month)) {
                alert("不可啟動未來月份簽核！");
                return;
            }
            if (parseInt(oth_month) < parseInt(kpi_month)) {
                oth_flag = true;
            }
            kpi_month = oth_month;
        } else {
            if (lock.indexOf("未鎖定") > 0) {
                alert("未鎖定，無法啟動簽核");
                return;
            }
        }

        if (confirm("確認啟動Flow簽核【" + kpi_month + "】？")) {
            //關閉則打開，未關閉則關閉
            showLoading();
            $.ajax({
                type: "post",
                url: "/Kpi/KpiFlowIniAct",
                data: {
                    //site: "EMCHS",
                    month: kpi_month,
                    oth_flag: oth_flag
                },
                success: function (data) {
                    hideLoading();
                    var result = JSON.parse(data);
                    if (result.flag) {
                        alert(result.msg);
                        btnKpiSearchClickAct('FP');
                    } else {
                        alert(result.msg);
                    }
                },
                error: function (err) {
                    hideLoading();
                }
            });
        }
    }

    //導出數據
    function ReportDataAct() {
        var tableTitle = $("#KpiActDataTd table thead tr")[0].children;
        var title = [];
        var index = [];
        for (var i = 3; i < 16; i++) {
            if (!tableTitle[i].hidden) {
                title.push(tableTitle[i].innerHTML.replace("<br>", ""));
                index.push(i - 3);
            }
        }
        index.push(13);
        index.push(14);
        index.splice(12, 1);
        index.splice(10, 1);
        index.splice(0, 1);

        var sel = $("#TxtKpiReportSel").val();
        var url = "/Kpi/ExportActual";
        if (sel == "2") {
            url = "/Kpi/ExportActualFailed";
        }

        showLoading();
        $.ajax({
            type: "post",
            url: url,
            data: {
                txtKpiSite: $("#TxtContractAct").val(),
                txtKpiYear: $("#TxtYearAct").val(),
                txtKpiNo: $("#TxtKpiNoAct").val(),
                txtKpiDesc: $("#TxtKpiDescAct").val(),
                txtKpiTarget: $("#TxtKpiTargetAct").val(),
                txtKpiDept: $("#TxtKpiDeptAct").val(),
                txtKpiPeriod: "M",
                txtKpiFreq: $("#TxtKpiFreqAct").val(),
                txtKpiInput: $("#TxtKpiInputAct").val(),
                txtKpiResult: $("#TxtKpiResultAct").val(),
                index: index.join(',')
            },
            success: function (data) {
                hideLoading();
                var result = JSON.parse(data);
                downloadFileAct(result.msg);
                setTimeout(function () {
                    deleteFileAct(result.msg);
                }, 5000);
            },
            error: function (err) {
                hideLoading();
            }
        });
    }
    //下載文件
    function downloadFileAct(fielPath) {
        var sel = $("#TxtKpiReportSel").val();
        var url = window.location.origin + "/Template/" + fielPath + "/Kpi實際匯總表.xlsx";
        if (sel == "2") {
            url = window.location.origin + "/Template/" + fielPath + "/Kpi差異分析表.xlsx";
        }
        window.open(url);
    }
    //刪除文件
    function deleteFileAct(fielPath) {
        $.ajax({
            type: "post",
            url: "/Kpi/DeleteTemplate",
            data: {
                filePath: fielPath
            },
            success: function (data) { },
            error: function (err) { }
        });
    }
    //標題全選
    function kpititelcheckChange(event) {
        var kpiactdatacheck = $(".kpiactdatacheck");
        for (var i = 0; i < kpiactdatacheck.length; i++) {
            kpiactdatacheck[i].checked = event.srcElement.checked;
        }
    }
    //內容全選
    function kpidatacheckChange(event) {
        if (event.srcElement.checked) {
            var kpiactdatacheck = $(".kpiactdatacheck");
            var checkeddata = 0;
            for (var i = 0; i < kpiactdatacheck.length; i++) {
                if (kpiactdatacheck[i].checked) {
                    checkeddata++;
                }
            }
            if (checkeddata == kpiactdatacheck.length && checkeddata > 0) {
                $("#kpititlecheck")[0].checked = true;
            }
        } else {
            $("#kpititlecheck")[0].checked = event.srcElement.checked;
        }
    }
    //根據內容合併行向單元格
    function tableRowSpan(colIndex1, colIndex2) {
        var tr = $(".kpiacttr");
        var td = $(".kpiacttr:eq(0)")[0];
        if (tr.length > 0 && td) {
            var colIndexS = colIndex1 < 0 || colIndex1 > td.cells.length ? 0 : colIndex1;
            var colIndexE = colIndex2 < 0 || colIndex2 > td.cells.length ? td.cells.length : colIndex2;
            if (colIndexS > colIndexE) {
                var tmpIndex;
                tmpIndex = colIndexE;
                colIndexE = colIndexS;
                colIndexS = tmpIndex;
            }
            var cellText;
            var nextCellText;
            var rowIndex;
            var rowspan;
            //var colorIndex = 0;
            for (var j = colIndexS; j <= colIndexE; j++) {
                cellText = "";
                nextCellText = "";
                rowIndex = 0;
                for (var i = 0; i < tr.length; i += 3) {
                    $(".kpiacttr:eq(" + i + ") td:eq(" + j + ")").css("background-color", "#eff3fb");
                    nextCellText = $(".kpiacttr:eq(" + i + ") td:eq(" + j + ")")[0].innerHTML;
                    if (cellText == "") {
                        rowIndex = i;
                        rowspan = 3;
                        cellText = nextCellText;
                        //$(".kpiacttr:eq(" + rowIndex + ") td:eq(" + j + ")").css("background-color", colorIndex % 2 == 0 ? "#eff3fb" : "#ffffff");
                        //colorIndex++;
                    } else {
                        if (cellText != nextCellText) {
                            rowIndex = i;
                            rowspan = 3;
                            cellText = nextCellText;
                            //$(".kpiacttr:eq(" + rowIndex + ") td:eq(" + j + ")").css("background-color", colorIndex % 2 == 0 ? "#eff3fb" : "#ffffff");
                            //colorIndex++;
                        } else if (cellText == nextCellText) {
                            rowspan += 3;
                            $(".kpiacttr:eq(" + rowIndex + ") td:eq(" + j + ")").attr("rowSpan", rowspan);
                            $(".kpiacttr:eq(" + i + ") td:eq(" + j + ")").hide();
                        }
                    }
                }
            }
        }
    }
    var editOthFlag = false;
    //編輯其他月份
    function editOth() {
        alert("請維護最新數據後，勾選保存！");
        editOthFlag = editOthFlag ? false : true;
        var nowMonth = new Date().getMonth();
        var tbody = $("#KpiActDataTd table tbody tr");
        var index = (tbody[0].cells.length - 17) / 6;
        var flag;
        for (var i = 0; i < tbody.length; i += 3) {
            for (var j = 1; j <= index; j++) {
                if (parseInt(tbody[i].cells[16 + j * 6].innerText) < nowMonth) {
                    flag = tbody[i].cells[12 + j * 6].children[0].disabled;
                    tbody[i + 1].cells[j].children[0].disabled = flag ? false : true;
                    tbody[i].cells[12 + j * 6].children[0].disabled = flag ? false : true;
                    tbody[i].cells[13 + j * 6].children[0].disabled = flag ? false : true;
                    tbody[i].cells[14 + j * 6].children[0].disabled = flag ? false : true;
                    tbody[i].cells[15 + j * 6].children[0].disabled = flag ? false : true;
                }
            }
        }
    }
    //添加是否修改標記
    function isChange(event) {
        event.target.isChange = true;
    }
    var datastr = "[@ViewBag.KpiMonthSel]";
    datastr = datastr.replaceAll("&quot;", '"');
    var dataitem = JSON.parse(datastr);
    var sel_data = new Date().getMonth().toString();
    sel_data = sel_data == "0" ? "12" : sel_data;
    //多選下拉框
    $('.provinces_region_box').dropdown({
        defaultdata: [{ "selected": false, "name": "全选", "id": "all" }], //默认数据-全选或不限
        data: dataitem,
        readonly: false, //是否禁用
        searchable: false, //下拉区域是否显示搜索框
        limitCount: 2000, //限制数据总量
        multipleMode: '', // 标记项模式 空字符串：文本模式 / 'label':标记项模式 / 'unfilling':内容不填充到输入框
        choice: function (ele) { //选中返回（多选）
            //console.log(ele);
            var data = [];
            for (var i = 0; i < ele.length; i++) {
                data.push(ele[i].id)
            }
            sel_data = data.join(',');
        },
        del: function () {
            //console.log('删除:', '初始化页面数据');
        },
        clearAll: function clearAll(event) {
            $("#TxtKpiMonthAct").val([]);
            sel_data = "0";
        }
    });
    $(function () {
        tableRowSpan(6, 7);
        updateLockInfo();
    });
</script>